package com.twotiger.and.activity.user;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.RegistVoiceBean;
import com.twotiger.and.bean.Register;
import com.twotiger.and.util.ActivitySwitcher;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.RegexTool;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

public class RegisterPage extends BaseActivity implements OnClickListener {

    private static final String TAG = "RegisterPage";

    private static final int SENDVCODESUCCES = 0;

    private static final int SENDVCODEFAIL = 1;

    private static final int TIMECOUNTMESSAGE = 2;

    private static final int CHECKVCODESUSSES = 3;

    private static final int CHECKVCODEFAIL = 4;

    protected static final int DISMISSDIAOLOG = 5;

    private String verify_type = null;//请求验证码返回的方式

    // 倒计时用计数
    private int time;
    // 按钮上的文字
    private String btnMsg = "";
    private Timer timer;

    private Button regist_button;
    private Button regist_verification_bt;
    private EditText regist_mobile_et;
    private EditText regist_verification_ev;
    private String mobile;

    private HashMap<String, String> params;

    private TextView sub_title_left_tv;

    private TextView sub_title_center_tv;

    private TextView tv_backtologin;

    private EditText invitation_edit;

    private TextView getvoice_vcode;
    private AlertDialog alertDialog;

    private ImageView iv_finish;
    private View register_root;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.register_layout, null);
        if ("forward".equals(getIntent().getStringExtra("isNeedAnim"))) {
            ActivitySwitcher.animationInForward(view, getWindowManager());
        }
        return view;
    }

    @Override
    protected void findViewById(View view) {
        regist_button = (Button) view.findViewById(R.id.regist_button);
        regist_verification_bt = (Button) view.findViewById(R.id.regist_verification_bt);
        tv_backtologin = (TextView) view.findViewById(R.id.tv_backtologin);
        sub_title_left_tv = (TextView) view.findViewById(R.id.sub_title_left_tv);
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        regist_mobile_et = (EditText) view.findViewById(R.id.regist_mobile_et);
        regist_verification_ev = (EditText) view.findViewById(R.id.regist_verification_ev);
        invitation_edit = (EditText) view.findViewById(R.id.invitation_edit);
        getvoice_vcode = (TextView) findViewById(R.id.getvoice_vcode);
        iv_finish = (ImageView) view.findViewById(R.id.iv_finish);
        register_root = view.findViewById(R.id.register_root);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.iv_finish:
            finish();
            overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
            break;
        case R.id.sub_title_left_tv:
            onBackPress();
            break;
        case R.id.regist_verification_bt: // 获取短信验证码
            mobile = regist_mobile_et.getText().toString().trim();
            if (StringUtils.isEmpty(mobile)) {
                showToast("请输入手机号");
                return;
            }
            ConstantDataUnit zz_sjh = getConstantDataByKey(Constants.zz_sjh);
            if (zz_sjh != null) {
                if (!RegexTool.match(zz_sjh.getVal(), mobile)) {
                    showToast("请输入有效手机号");
                    return;
                }
            } else {
                if (!RegexTool.regexPhoneNumber(mobile)) {
                    showToast("请输入有效手机号");
                    return;
                }
            }
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            verify_type = "sms";
            getVcode(mobile, verify_type);
            break;
        case R.id.tv_backtologin:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            //            Intent intent = new Intent(this, LoginPage.class);
            //            intent.putExtra("FROM", R.id.tv_backtologin);
            //            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);

            final Intent intent1 = new Intent(getApplicationContext(), LoginPage.class);
            intent1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            ActivitySwitcher.animationOutBack(register_root, getWindowManager(),
                new ActivitySwitcher.AnimationFinishedListener() {
                    @Override
                    public void onAnimationFinished() {
                        startNewActivity(intent1.putExtra("isNeedAnim", "back"), 0, 0, true);
                    }
                });
            break;
        case R.id.getvoice_vcode: //获取语音验证码
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            mobile = regist_mobile_et.getText().toString().trim();
            if (StringUtils.isEmpty(mobile)) {
                showToast("请输入手机号");
                return;
            }
            ConstantDataUnit zz_sjh_2 = getConstantDataByKey(Constants.zz_sjh);
            if (zz_sjh_2 != null) {
                if (!RegexTool.match(zz_sjh_2.getVal(), mobile)) {
                    showToast("请输入有效手机号");
                    return;
                }
            } else {
                if (!RegexTool.regexPhoneNumber(mobile)) {
                    showToast("请输入有效手机号");
                    return;
                }
            }
            verify_type = "voice";
            getVcode(mobile, verify_type);

            break;
        case R.id.regist_button:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String verification_code = regist_verification_ev.getText().toString().trim();
            mobile = regist_mobile_et.getText().toString().trim();
            // 用户名：请用字母、数字、下划线,至少6个字符 "^([a-zA-Z0-9_]){6,20}$"
            params.clear();
            params.put("phone", mobile);
            params.put("code", verification_code);
            getDate(params, Constants.VERIFYCAP, handler, CHECKVCODESUSSES, CHECKVCODEFAIL, true,
                false, false);
            break;
        }
    }

    private void getVcode(String phone, String type) {
        params.clear();
        params.put("phone", phone);
        params.put("type", type);

        getDate(params, Constants.CAPTCHAREGIST, handler, SENDVCODESUCCES, SENDVCODEFAIL, true,
            false, false);
    }

    @Override
    protected void setListener() {
        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case SENDVCODESUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        Basebean responseinfo = JSONObject.parseObject(result.data, Basebean.class);
                        if ("sms".equals(verify_type)) {
                            showToast("验证码已经发送至您的手机，请注意查收");
                            timer_show();
                        } else if ("voice".equals(verify_type)) {
                            RegistVoiceBean voiceVcode = JSONObject.parseObject(
                                (String) result.data, RegistVoiceBean.class);

                            alertDialog = PromptManager.showConfirmAlertCommon(mContext, 0, "",
                                "请等待10s\n" + voiceVcode.getVoicePhone() + "将为您播报语音验证码", "确定", "",
                                false, new ReChargeClickListener() {

                                    @Override
                                    public void onClickConfirm() {

                                    }

                                    @Override
                                    public void onClickCancel() {

                                    }
                                });

                            new Thread(new Runnable() {
                                public void run() {
                                    SystemClock.sleep(5000);
                                    handler.sendEmptyMessage(DISMISSDIAOLOG);
                                }
                            }) {
                            }.start();
                        }
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case SENDVCODEFAIL:

                    break;
                case TIMECOUNTMESSAGE:
                    regist_verification_bt.setEnabled(true);
                    // 设置为原有的text
                    regist_verification_bt.setText(btnMsg);
                    // timer 取消执行
                    timer.cancel();
                    break;
                case CHECKVCODESUSSES:
                    Basebean result_v = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_v.isOk()) {
                        Register register = JSONObject.parseObject(result_v.data, Register.class);
                        //                        Intent intent = new Intent(getContext(), RegistNextpage.class);
                        //                        intent.putExtra("registToken", register.token);
                        //                        String inviteCode = invitation_edit.getText().toString().trim();
                        //                        if (!TextUtils.isEmpty(inviteCode)) {
                        //                            intent.putExtra("inviteCode", inviteCode);
                        //                        }
                        //                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);

                        final Intent intent = new Intent(getApplicationContext(),
                            RegistNextpage.class);
                        intent.putExtra("registToken", register.token);
                        String inviteCode = invitation_edit.getText().toString().trim();
                        if (!TextUtils.isEmpty(inviteCode)) {
                            intent.putExtra("inviteCode", inviteCode);
                        }
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        ActivitySwitcher.animationOutForward(register_root, getWindowManager(),
                            new ActivitySwitcher.AnimationFinishedListener() {
                                @Override
                                public void onAnimationFinished() {
                                    startNewActivity(intent.putExtra("isNeedAnim", "forward"), 0,
                                        0, true);
                                }
                            });

                    } else {
                        showToast(result_v.codeDesc);
                    }

                    break;
                case CHECKVCODEFAIL:

                    break;
                case DISMISSDIAOLOG:
                    if (alertDialog != null && alertDialog.isShowing()) {
                        alertDialog.dismiss();
                    }
                    ;
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        iv_finish.setOnClickListener(this);
        tv_backtologin.setOnClickListener(this);
        regist_verification_bt.setOnClickListener(this);
        regist_button.setOnClickListener(this);
        sub_title_left_tv.setOnClickListener(this);
        getvoice_vcode.setOnClickListener(this);
        regist_mobile_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s) || s.length() != 11 || !StringUtils.isEmpty(mobile)) {
                    regist_button.setEnabled(false);
                } else {
                    regist_button.setEnabled(true);
                }

            }
        });
        regist_verification_ev.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    regist_button.setEnabled(false);
                } else {
                    regist_button.setEnabled(true);
                }

            }
        });
    }

    @Override
    protected void onRestart() {
        if (getRegistTag()) {
            finish();
        }
        super.onRestart();
    }

    @Override
    protected void processLogic() {
        params = getParm();
        initPage();
    }

    private void initPage() {
        sub_title_center_tv.setText("注册");
        sub_title_left_tv.setText("取消");
        sub_title_left_tv.setTextColor(getResources().getColor(R.color.gray_1));
        sub_title_left_tv.setVisibility(View.VISIBLE);
        // 初始化标题
    }

    @SuppressLint("NewApi")
    private void timer_show() {
        time = 60;
        btnMsg = regist_verification_bt.getText().toString();
        // 设置按钮不可点击
        regist_verification_bt.setEnabled(false);
        timer = new Timer();
        // 点击1毫秒开始执行，没个一秒执行一次
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                int i = getInt();
                regist_verification_bt.post(new ButtonTextFresh(i));
                // 若倒计时到0时
                if (i == 0) {
                    handler.sendEmptyMessage(TIMECOUNTMESSAGE);
                }
            }
        }, 1, 1000);
    }

    /**
     * 获取倒计时的计数
     * 
     * @return
     */
    private int getInt() {
        return time--;
    }

    class ButtonTextFresh implements Runnable {

        private int iMsg;

        public ButtonTextFresh(int iMsg) {
            this.iMsg = iMsg;
        }

        @Override
        public void run() {
            regist_verification_bt.setText(btnMsg + "(" + iMsg + ")");
        }
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
    }

}
